<?php

class Default_IndexController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    public function indexAction() {

        $dir = "\public\\files\\";
        $dirLink = "/files/";

        $form = new UndeadStudents_Forms_Upload();
        $form_search = new UndeadStudents_Forms_Search();

        $this->view->form = $form;
        $this->view->form_search = $form_search;

        //sending file to upload
        if ($this->_request->isPost()) {

            $data = $this->_request->getPost();

            if ($form->isValid($data)) {

                unset($data['submit']);
                $this->upload($form, $data);
                unset($data['file']);
                unset($data['MAX_FILE_SIZE']);

                //saving file database
                $file_name = $form->getElement('file')->getValue();
                $file['description'] = $data['description'];
                $file['path'] = $dirLink . $file_name;
                $file['name'] = $file_name;
                $this->saveFile($file);
            }
        }

        $fileModel = new Application_Model_File();
        $searchList = $fileModel->search('');
        $this->view->files_list = $searchList;
    }

    public function newAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
    }

    public function searchAction() {

        $form = new UndeadStudents_Forms_Upload();
        $form_search = new UndeadStudents_Forms_Search();

        $this->view->form = $form;
        $this->view->form_search = $form_search;

        if ($this->_request->isPost()) {
            $data = $this->_request->getPost();

            if ($form_search->isValid($data)) {
                $file = new Application_Model_File();
                $searchList = $file->search($data['search']);
                $this->view->files_list = $searchList;
                $this->view->render('index');
            }
        }
    }

    private function upload($form, $data) {
        if ($form->getElement('file')->isUploaded()) {
            $file = $form->getElement('file');
            $file->setDestination('files')->setValueDisabled(true);
            $file->receive();
        }
    }

    private function saveFile(array $data) {
        $file = new Application_Model_File();
        $file->save($data);
    }

}